package com.xywy.start;

import java.util.Calendar;
import java.util.HashMap;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.xywy.R;
import com.xywy.common.BaseActivity;
import com.xywy.common.FragmentMainActivity;
import com.xywy.common.constants.ResultCode;
import com.xywy.common.net.AsyncHttpClient;
import com.xywy.common.net.OnResultListenerAdapter;
import com.xywy.common.net.Parser;
import com.xywy.common.util.CalendarUtil;
import com.xywy.common.util.MLog;
import com.xywy.common.widget.MyProgress;
import com.xywy.common.widget.TitleBar;
import com.xywy.me.SetupAcValMobileActivity;
import com.xywy.me.bean.User;
import com.xywy.me.bean.UserKeeper;
import com.xywy.start.widget.wheel.ArrayWheelAdapter;
import com.xywy.start.widget.wheel.OnWheelChangedListener;
import com.xywy.start.widget.wheel.WheelView;

/**
 * @ClassName: BirthActivity
 * @Package com.xywy.start
 * @Description:生日頁,上传身高、性别、姓名 或者跳转至快速注册
 * @author CodeMonkeyCui
 * @date 2014年11月6日 下午1:16:26
 * @version V1.0
 */
public class BirthActivity extends BaseActivity {
	private static final String TAG = "BirthActivity";
	private LinearLayout layout = null;

	private WheelView yearWV = null;
	private WheelView monthWV = null;
	private WheelView dayWV = null;

	int year;
	int month;

	// 滚轮上的数据，字符串数组
	String[] yearArrayString = null;
	String[] dayArrayString = null;
	String[] monthArrayString = null;
	Calendar c = null;
	String dateStr = null;

	private int sex;
	private int height;
	private Parser paramsParser;
	private HashMap<String, Object> params;
	private AsyncHttpClient asyncHttpClient;
	private Context mContext;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// 设置为全屏
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.start_birth);

		this.preInit();
		this.initView();
		this.setListener();
	}

	public void startOnClick(View view) {
		switch (view.getId()) {
		case R.id.bt_birth_next:
			if (userid != null) {
				bindInfo();
				// String dateStr2 = CalendarUtil.getTimstamp(dateStr);
				// Intent intent = new Intent(this,);
				// intent.putExtra("userid", userid);
				// intent.putExtra("sex", sex);
				// intent.putExtra("height", height);
				// intent.putExtra("birthday", dateStr2);
			} else {
				next();
			}
			break;
		}
		;
	}

	/**
	 * 绑定身高，性别，年龄
	 */
	private void bindInfo() {
		// TODO Auto-generated method stub
		sendMsg();

	}

	MyProgress myProgress;

	/**
	 * 发送网络请求,添加height,sex,birthday的值
	 */
	public void sendMsg() {
		myProgress = new MyProgress(this, 10);
		myProgress.start();
		paramsParser = new Parser();

		// 封装参数
		params = new HashMap<String, Object>();

		// 请求路径
		paramsParser.action = getString(R.string.update_user_infor);
		// 请求方式
		paramsParser.request = "post";

		// 请求参数
		String dateStr2 = CalendarUtil.getTimstamp(dateStr);
		params.put("userid", userid);
		params.put("height", height);
		params.put("sex", sex);
		params.put("birthday", dateStr2);
		params.put("keyword", "edit");

		paramsParser.map = params;
		// 传递上下文
		paramsParser.context = this.context;

		asyncHttpClient = AsyncHttpClient.getInstance();
		asyncHttpClient.exeute(paramsParser, onResultListenerAdapter);
	}

	OnResultListenerAdapter onResultListenerAdapter = new OnResultListenerAdapter() {
		@Override
		public <T extends Parser> void onSuccess(T resultParser, int resultCode) {
			super.onSuccess(resultParser, resultCode);
			Message message = Message.obtain();
			message.arg1 = resultCode;
			message.obj = resultParser.back;
			handler.sendMessage(message);
		}
	};
	JSONObject msgBack;
	/**
	 * 返回
	 */
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			MLog.i(TAG, "back:" + msg.obj + "resuletCode:" + msg.arg1);
			myProgress.stop();
			if (null != msg.obj) {
				try {
					msgBack = new JSONObject(msg.obj.toString());
				} catch (JSONException e) {
					e.printStackTrace();
				}
				if (msgBack.optInt("state") == ResultCode.SUCCESS) {
					int height = msgBack.optInt("height");
					MLog.i(TAG, "当前账户的height" + height);
					String userid = msgBack.optString("userid");

					MLog.i(TAG, "当前人的userid:" + userid);
					int isregister = msgBack.optInt("isregister");
					if (isregister == 0) {
						Intent intent = new Intent(mContext, SetupAcValMobileActivity.class);
						intent.putExtra("userid", userid);
						mContext.startActivity(intent);
						finish();
					} else {
						User user = UserKeeper.getCurrentUser(BirthActivity.this);
						user.setHeight(height+"");
						if(sex ==1){
							user.setSex("男");
						}else if(sex ==2){
							user.setSex("女");
						}
						UserKeeper.saveUser(user, BirthActivity.this);
						UserKeeper.getUserAvatar(BirthActivity.this, user, AvatarHandler);
//						Intent intent = new Intent(mContext, FragmentMainActivity.class);
//						mContext.startActivity(intent);
//						finish();
					}

					// if (height == 0) {
					//
					// // Intent intent = new Intent(mContext,
					// // HeightActivity.class);
					// // intent.putExtra("userid", userid);
					// // mContext.startActivity(intent);
					//
					// } else {

					// 将 userid 存入本地
					// SharedPreferences sp = context.getSharedPreferences(
					// "config", Context.MODE_PRIVATE);
					// SharedPreferences.Editor editor = sp.edit();
					// editor.putString("userid", userid);
					// editor.putString("mobile",
					// account.getText().toString());

					// editor.commit();

					// }

				} else {
					Toast.makeText(mContext, msgBack.optString("error"), Toast.LENGTH_LONG).show();
					return;
				}
			}
		}
	};
	
	
	Handler AvatarHandler = new Handler(){
		public void handleMessage(Message msg) {
			myProgress.stop();
			switch (msg.what) {
			case ResultCode.NULL:
				Toast.makeText(BirthActivity.this, "服务器返回异常", Toast.LENGTH_SHORT).show();
				break;
			case ResultCode.FAIL:
				Toast.makeText(BirthActivity.this, "网络异常,请稍后重试", Toast.LENGTH_SHORT).show();
				break;
			case ResultCode.SUCCESS:
				Intent intent = new Intent(mContext,
						FragmentMainActivity.class);
				mContext.startActivity(intent);
				break;

			default:
				break;
			}
		};
	};
	

	private void next() {

		String dateStr2 = CalendarUtil.getTimstamp(dateStr);
		MLog.i(TAG, "选择后的年月日为:" + dateStr + "  转换为时间戳:" + dateStr2);
		Intent intent = new Intent(this, RegisterActivity.class);
		// if (userid != null) {
		// intent.putExtra("userid", userid);
		// }
		intent.putExtra("sex", sex);
		intent.putExtra("height", height);
		intent.putExtra("birthday", dateStr2);
		startActivity(intent);
	}

	@Override
	protected void onResume() {
		super.onResume();

	}

	@Override
	protected void onPause() {
		super.onPause();

	}

	private String target = "";
	private String userid;

	public void preInit() {
		mContext = this.context;
		Intent intent = this.getIntent();
		sex = intent.getIntExtra("sex", 0);
		height = intent.getIntExtra("height", 0);
		target = intent.getStringExtra("target");
		userid = intent.getStringExtra("userid");
		MLog.i(TAG, "SEX=====" + sex + "   height:" + height);
	}

	@Override
	public void loadData() {

	}

	private TextView tvBack;
	private Button bt_birth_next;

	public void initView() {
		// title
		TitleBar titleBar = (TitleBar) findViewById(R.id.title_bar);
		TextView tvTitle = titleBar.getTitle();
		tvTitle.setText(getString(R.string.tv_start_birth));
		tvBack = titleBar.getTvBack();

		// 日期滚动
		layout = (LinearLayout) findViewById(R.id.ll_birthday);
		// 得到相应的数组
		yearArrayString = getYEARArray(1900, 102);
		monthArrayString = getDayArray(12);

		// 获取当前系统时间
		c = Calendar.getInstance();

		yearWV = (WheelView) findViewById(R.id.time_year);
		monthWV = (WheelView) findViewById(R.id.time_month);
		dayWV = (WheelView) findViewById(R.id.time_day);

		// 设置每个滚轮的行数
		yearWV.setVisibleItems(7);
		monthWV.setVisibleItems(7);
		dayWV.setVisibleItems(7);

		yearWV.setCyclic(true);
		monthWV.setCyclic(true);
		dayWV.setCyclic(true);
		bt_birth_next = (Button) findViewById(R.id.bt_birth_next);
		setData();
	}

	/**
	 * 给滚轮提供数据
	 */
	private void setData() {
		// 给滚轮提供数据
		yearWV.setAdapter(new ArrayWheelAdapter<String>(yearArrayString));
		monthWV.setAdapter(new ArrayWheelAdapter<String>(monthArrayString));

		yearWV.addChangingListener(new OnWheelChangedListener() {
			@Override
			public void onChanged(WheelView wheel, int oldValue, int newValue) {
				// 获取年和月
				year = Integer.parseInt(yearArrayString[yearWV.getCurrentItem()]);
				month = Integer.parseInt(monthArrayString[monthWV.getCurrentItem()]);
				// 根据年和月生成天数数组
				dayArrayString = getDayArray(getDay(year, month));
				// 给天数的滚轮设置数据
				dayWV.setAdapter(new ArrayWheelAdapter<String>(dayArrayString));
				// 防止数组越界
				if (dayWV.getCurrentItem() >= dayArrayString.length) {
					dayWV.setCurrentItem(dayArrayString.length - 1);
				}
				// 显示的时间
				showDate();
			}
		});

		// 当月变化时显示的时间
		monthWV.addChangingListener(new OnWheelChangedListener() {

			@Override
			public void onChanged(WheelView wheel, int oldValue, int newValue) {
				// 获取年和月
				year = Integer.parseInt(yearArrayString[yearWV.getCurrentItem()]);
				month = Integer.parseInt(monthArrayString[monthWV.getCurrentItem()]);
				// 根据年和月生成天数数组
				dayArrayString = getDayArray(getDay(year, month));
				// 给天数的滚轮设置数据
				dayWV.setAdapter(new ArrayWheelAdapter<String>(dayArrayString));
				// 防止数组越界
				if (dayWV.getCurrentItem() >= dayArrayString.length) {
					dayWV.setCurrentItem(dayArrayString.length - 1);
				}
				// 显示的时间
				showDate();
			}
		});

		// 当天变化时，显示的时间
		dayWV.addChangingListener(new OnWheelChangedListener() {
			@Override
			public void onChanged(WheelView wheel, int oldValue, int newValue) {
				showDate();
			}
		});

		// 把当前系统时间显示为滚轮默认时间
		setOriTime();
	}

	// 设定初始时间 c.get(Calendar.YEAR)
	void setOriTime() {
		yearWV.setCurrentItem(getNumData(1992 + "", yearArrayString));
		monthWV.setCurrentItem(getNumData(c.get(Calendar.MONTH) + 1 + "", monthArrayString) + 0);

		dayArrayString = getDayArray(getDay(year, month));
		dayWV.setAdapter(new ArrayWheelAdapter<String>(dayArrayString));
		dayWV.setCurrentItem(getNumData(c.get(Calendar.DAY_OF_MONTH) + "", dayArrayString));

		// 初始化显示的时间
		showDate();
	}

	// 显示时间
	void showDate() {
		createDate(yearArrayString[yearWV.getCurrentItem()], monthArrayString[monthWV.getCurrentItem()], dayArrayString[dayWV.getCurrentItem()]);
	}

	// 生成时间
	void createDate(String year, String month, String day) {
		dateStr = year + "-" + month + "-" + day;
	}

	// 在数组Array[]中找出字符串s的位置
	int getNumData(String s, String[] Array) {
		int num = 0;
		for (int i = 0; i < Array.length; i++) {
			if (s.equals(Array[i])) {
				num = i;
				break;
			}
		}
		return num;
	}

	// 根据当前年份和月份判断这个月的天数
	public int getDay(int year, int month) {
		int day;
		if (year % 4 == 0 && year % 100 != 0) { // 闰年
			if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {
				day = 31;
			} else if (month == 2) {
				day = 29;
			} else {
				day = 30;
			}
		} else { // 平年
			if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {
				day = 31;
			} else if (month == 2) {
				day = 28;
			} else {
				day = 30;
			}
		}
		return day;
	}

	// 根据数字生成一个字符串数组
	public String[] getDayArray(int day) {
		String[] dayArr = new String[day];
		for (int i = 0; i < day; i++) {
			dayArr[i] = i + 1 + "";
		}
		return dayArr;
	}

	// 根据数字生成一个字符串数组
	public String[] getHMArray(int day) {
		String[] dayArr = new String[day];
		for (int i = 0; i < day; i++) {
			dayArr[i] = i + "";
		}
		return dayArr;
	}

	// 根据初始值start和step得到一个字符数组，自start起至start+step-1
	public String[] getYEARArray(int start, int step) {
		String[] dayArr = new String[step];
		for (int i = 0; i < step; i++) {
			dayArr[i] = start + i + "";
		}
		return dayArr;
	}

	@Override
	public void onBackPressed() {
		back();
		super.onBackPressed();
	}

	private void setListener() {
		tvBack.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				back();
			}
		});
	}

	private void back() {
		finish();
	}
}
